<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <h2>用户注册</h2>
        <p>加入茶叶溯源系统，参与透明的茶叶供应链</p>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        label-position="top"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="2-50个字符"
                size="large"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="registerForm.email"
                type="email"
                placeholder="用于登录和通知"
                size="large"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="至少6位，包含字母和数字"
                size="large"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                size="large"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="选填，用于重要通知"
            size="large"
          />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select
            v-model="registerForm.role"
            placeholder="请选择您的角色"
            size="large"
            class="role-select"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            >
              <div class="role-option">
                <span class="role-label">{{ role.label }}</span>
                <span class="role-desc">{{ role.description }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 个人信息 -->
        <el-divider content-position="left">个人信息 (选填)</el-divider>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="姓名" prop="profile.name">
              <el-input
                v-model="registerForm.profile.name"
                placeholder="真实姓名或企业名称"
                size="large"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="profile.location">
              <el-input
                v-model="registerForm.profile.location"
                placeholder="省市区详细地址"
                size="large"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-checkbox v-model="agreeTerms" size="large">
            我已阅读并同意
            <el-link type="primary" @click="showTerms">用户协议</el-link>
            和
            <el-link type="primary" @click="showPrivacy">隐私政策</el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            :disabled="!agreeTerms"
            @click="handleRegister"
            class="register-btn"
          >
            注册
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="login-link">
            <span>已有账户？</span>
            <el-link type="primary" @click="goToLogin">
              立即登录
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const registerFormRef = ref(null)

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  phone: '',
  role: '',
  profile: {
    name: '',
    location: ''
  }
})

// 角色选项
const roleOptions = [
  {
    value: 'farmer',
    label: '茶农',
    description: '种植和生产茶叶'
  },
  {
    value: 'logistics',
    label: '物流方',
    description: '负责茶叶运输'
  },
  {
    value: 'merchant',
    label: '商家',
    description: '销售茶叶给消费者'
  },
  {
    value: 'consumer',
    label: '消费者',
    description: '购买和查询茶叶信息'
  }
]

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 50, message: '用户名长度在2-50个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_-]+$/, message: '用户名只能包含字母、数字、中文、下划线和连字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { pattern: /^[\+]?[1-9][\d]{0,15}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  'profile.name': [
    { max: 100, message: '姓名长度不能超过100个字符', trigger: 'blur' }
  ],
  'profile.location': [
    { max: 200, message: '地址长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 状态
const loading = ref(false)
const agreeTerms = ref(false)

// 方法
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    
    if (!agreeTerms.value) {
      ElMessage.warning('请先同意用户协议和隐私政策')
      return
    }
    
    loading.value = true
    
    // 准备注册数据
    const registerData = {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      phone: registerForm.phone || undefined,
      role: registerForm.role,
      profile: {
        name: registerForm.profile.name || undefined,
        location: registerForm.profile.location || undefined
      }
    }
    
    // 清理空值
    Object.keys(registerData.profile).forEach(key => {
      if (!registerData.profile[key]) {
        delete registerData.profile[key]
      }
    })
    
    if (Object.keys(registerData.profile).length === 0) {
      delete registerData.profile
    }
    
    const result = await authStore.register(registerData)
    
    if (result.success) {
      ElMessage.success('注册成功！')
      router.push('/dashboard')
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    if (error !== false) {  // 排除表单验证失败
      console.error('注册失败:', error)
      ElMessage.error('注册失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const showTerms = () => {
  ElMessage.info('用户协议功能开发中')
}

const showPrivacy = () => {
  ElMessage.info('隐私政策功能开发中')
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  width: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 600;
}

.register-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.register-form {
  width: 100%;
}

.role-select {
  width: 100%;
}

.role-option {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.role-label {
  font-weight: 500;
  color: #2c3e50;
}

.role-desc {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 2px;
}

.register-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
}

.login-link {
  text-align: center;
  width: 100%;
}

.login-link span {
  color: #7f8c8d;
  margin-right: 8px;
}

/* 响应式 */
@media (max-width: 768px) {
  .register-card {
    width: 100%;
    max-width: 500px;
    padding: 30px 20px;
  }
  
  .register-container {
    padding: 16px;
  }
}
</style>